package com.nft.service.school.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nft.constant.response.ResponseConstants;
import com.nft.paging.Paginator;
import com.nft.po.NftResponse;
import com.nft.service.school.entity.*;
import com.nft.service.school.mapper.SchoolClassesMapper;
import com.nft.service.school.mapper.SchoolConsumeMapper;
import com.nft.service.school.mapper.SchoolStudentMapper;
import com.nft.service.school.mapper.SysUserMapper;
import com.nft.service.school.req.SchoolClassesReq;
import com.nft.service.school.req.SysUserReq;
import com.nft.service.school.resp.SchoolClassesResp;
import com.nft.service.school.service.SchoolClassesService;
import com.nft.utils.query.QueryUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SchoolClassesServiceImpl extends ServiceImpl<SchoolClassesMapper, SchoolClassesEntity> implements SchoolClassesService {
    @Resource
    private StringRedisTemplate myRedisTemplate;
    @Autowired
    private SchoolStudentMapper schoolStudentMapper;
    @Autowired
    private SchoolConsumeMapper schoolConsumeMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public NftResponse<Paginator<SchoolClassesResp>> getClassesList(SchoolClassesReq query) {
        if (query.getPageNo() == null || query.getPageNo() <= 0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "入参页码错误", null);
        }
        if (query.getPageSize() == null || query.getPageSize() <= 0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "入参每页数量错误", null);
        }
        Paginator<SchoolClassesResp> paginator = new Paginator<SchoolClassesResp>(query.getPageNo(), query.getPageSize(), 0, new ArrayList<>());
        List<SchoolClassesEntity> records = new ArrayList<>();
        Map<Object, Object> mapValue = myRedisTemplate.opsForHash().entries("CLASS:DATA");
        if (mapValue.isEmpty()) {
            QueryWrapper<SchoolClassesEntity> wrapperQuery = new QueryWrapper<>();
            List<SchoolClassesEntity> classList = this.baseMapper.selectList(wrapperQuery);
            mapValue = new HashMap<>();
            for (SchoolClassesEntity obj:classList) {
                mapValue.put(obj.getId()+"", JSON.toJSONString(obj));
            }
            myRedisTemplate.opsForHash().putAll("CLASS:DATA", mapValue);
        }
        for (Map.Entry<Object, Object> entry : mapValue.entrySet()) {
            SchoolClassesEntity entity = JSON.parseObject(entry.getValue().toString(), SchoolClassesEntity.class);
            records.add(entity);
        }
        List<SchoolClassesResp> pageResult = BeanUtil.copyToList(records, SchoolClassesResp.class);
        paginator.setPageNo(query.getPageNo());
        paginator.setPageSize(query.getPageSize());
        paginator.setTotalDataNum(records.size());
        paginator.setPageData(pageResult);
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "获取成功", paginator);
    }

    @Override
    public NftResponse<List<SchoolClassesResp>> getClassesListByUserId(SysUserReq query) {
        List<Long> classesIds = new ArrayList<>();
        List<Long> schoolIds = new ArrayList<>();
        QueryWrapper<SchoolClassesEntity> wrapperQuery = new QueryWrapper<>();
        Map<Object, Object> mapValue = null;
        if (null!=query.getSchoolId()&&!"".equals(query.getSchoolId())) {
            mapValue = myRedisTemplate.opsForHash().entries("CLASS:DATA:"+query.getSchoolId());
            wrapperQuery.eq(QueryUtil.camelToUnderline("schoolId"), query.getSchoolId());
        }else {
            mapValue = myRedisTemplate.opsForHash().entries("CLASS:DATA");
        }
        List<SchoolClassesEntity> list = new ArrayList<>();
        if (mapValue.isEmpty()) {
            List<SchoolClassesEntity> alllist = this.baseMapper.selectList(wrapperQuery);
            mapValue = new HashMap<>();
            for (SchoolClassesEntity obj:alllist) {
                mapValue.put(obj.getId()+"", JSON.toJSONString(obj));
            }
            if (null!=query.getSchoolId()&&!"".equals(query.getSchoolId())) {
                myRedisTemplate.opsForHash().putAll("CLASS:DATA:"+query.getSchoolId(), mapValue);
            }else {
                myRedisTemplate.opsForHash().putAll("CLASS:DATA", mapValue);
            }
        }
        if (null!=query.getJwteacherId()||null!=query.getJxteacherId()) {
            for (Map.Entry<Object, Object> entry : mapValue.entrySet()) {
                SchoolClassesEntity entity = JSON.parseObject(entry.getValue().toString(), SchoolClassesEntity.class);
                if (null!=query.getJxteacherId()&&!"".equals(query.getJxteacherId())&&(entity.getJwteacherId()==query.getJxteacherId()||entity.getJxteacherId()==query.getJxteacherId())) {
                    classesIds.add(entity.getId());
                }
            }
        }
        QueryWrapper<SysUserEntity> wrapperUser = new QueryWrapper<>();
        wrapperUser.eq(QueryUtil.camelToUnderline("phonenumber"), query.getPhone());
        wrapperUser.eq(QueryUtil.camelToUnderline("delFlag"),"0");
        wrapperUser.eq(QueryUtil.camelToUnderline("status"), "0");
        List<SysUserEntity> users = sysUserMapper.selectList(wrapperUser);
        if (null!=query.getTeacherId()) {
            for (SysUserEntity user:users) {
                schoolIds.add(user.getDeptId());
                QueryWrapper<SchoolConsumeEntity> wrapperQueryConsume = new QueryWrapper<>();
                wrapperQueryConsume.eq(QueryUtil.camelToUnderline("teacherId"), user.getUserId());
                List<SchoolConsumeEntity> consumeList = schoolConsumeMapper.selectList(wrapperQueryConsume);
                for (SchoolConsumeEntity obj : consumeList) {
                    classesIds.add(obj.getClassesId());
                }
            }
        }else {
            for (SysUserEntity user:users) {
                schoolIds.add(user.getDeptId());
                QueryWrapper<SchoolStudentEntity> wrapperQueryUser = new QueryWrapper<>();
                wrapperQueryUser.eq(QueryUtil.camelToUnderline("studentId"), user.getUserId());
                List<SchoolStudentEntity> studentList = schoolStudentMapper.selectList(wrapperQueryUser);
                for (SchoolStudentEntity obj:studentList) {
                    classesIds.add(obj.getClassesId());
                }
            }
        }
        if (null!=query.getSchoolId()&&!"".equals(query.getSchoolId())) {
            for (Map.Entry<Object, Object> entry : mapValue.entrySet()) {
                SchoolClassesEntity entity = JSON.parseObject(entry.getValue().toString(), SchoolClassesEntity.class);
                list.add(entity);
            }
        }else {
            for (Map.Entry<Object, Object> entry : mapValue.entrySet()) {
                SchoolClassesEntity entity = JSON.parseObject(entry.getValue().toString(), SchoolClassesEntity.class);
                if (schoolIds.contains(entity.getSchoolId())) {
                    list.add(entity);
                }
            }
        }
        List<SchoolClassesResp> result = BeanUtil.copyToList(list, SchoolClassesResp.class);
        for (SchoolClassesResp obj:result) {
            if (classesIds.contains(obj.getId())) {
                obj.setIsMe(true);
            }else {
                obj.setIsMe(false);
            }
        }
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "获取成功", result);
    }
}
